package chpt11;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class InetAddressTest {

	public static void main(String[] args) throws UnknownHostException {
		String host = "www.oracle.com";
		System.out.println("演示1：获取指定主机名对应的所有IP");
		InetAddress[] addressArr = InetAddress.getAllByName(host);
		for (InetAddress e : addressArr) {
			System.out.println(e);// 主机名/地址
		}
       // 通过主机名找ip
		System.out.println("\n演示2：获取指定主机名获得ip");
		InetAddress ip1 = InetAddress.getByName(host);
		System.out.printf("ip1 %s : %s%n", host, ip1);

		// 通过byte数组获取InetAddress，然后返回主机名
		System.out.println("\n演示3：根据byte数组获得ip");
		byte[] address = ip1.getAddress();
		InetAddress ip2 = InetAddress.getByAddress(address);
		System.out.println("ip1 == ip2: " + ip1.equals(ip2));
		System.out.print("IP2 address: " + ip2.getHostAddress());
		System.out.println(", hostname: " + ip2.getHostName());

		System.out.println("\n演示4：根据指定ip获得主机名");
		String ipStr = "104.86.224.128";
		InetAddress ip3 = InetAddress.getByName(ipStr);
		System.out.println("ip " + ipStr + " 的主机名: " + ip3.getHostName());
		
		System.out.println("\n演示5：本地主机演示：");
		// 获取本地主机的InetAddress
		InetAddress localIP = InetAddress.getLocalHost();
		// 获取该地址对应的主机名(字符串格式)
		String hostName = localIP.getHostName();
		// 获取该地址对应的IP(字符串格式)
		String hostAddress = localIP.getHostAddress();
		System.out.printf("HostName: %s, ip: %s%n", hostName, hostAddress);
	}
}

